//
//  WCNWoundVC.m
//  WCN
//
//  Created by 陈武琦 on 16/3/31.
//  Copyright © 2016年 ShanghaiCize Trade And Business Co., Ltd. All rights reserved.
//

#import "WCNWoundRecordVC.h"
#import "WCNWoundRecordCell.h"
#import "WCImageManager.h"
#import "MJRefresh.h"
#import "WCNWoundDetailVC.h"
#import "WCNPatientClassTHFV.h"
#import "WCNPatientHospitalTCell.h"
#import "WCNPatientHomeTCell.h"
#import "WCNPatientAddVC.h"
#import "WCNParentCareRecordVC.h"
#import "Patient.h"
#import "Constants.h"
#import "JCAlertView.h"
#import "NSDate+Category.h"
#import "WCButton.h"
#import "UINavigationItem+Offset.h"
#import "RWDropdownMenu.h"
#import "WCWeixinTool.h"
#import "WoundRecord.h"


static NSString *cellId1 = @"WCNPatientHospitalTCell";
static NSString *cellid2 = @"WCNPatientHomeTCell";
static NSString *cellId = @"WCNWoundRecordCellId";
static NSString *headerId = @"WCNPatientClassTHFVID";
@interface WCNWoundRecordVC ()<UITableViewDataSource, UITableViewDelegate, UIActionSheetDelegate>
@property (weak, nonatomic) MBProgressHUD *hud;
//上拉加载的页面
@property (nonatomic, assign) NSInteger page;
//最大页数
@property (nonatomic, assign) NSInteger totalPage;
@property (strong, nonatomic) Patient *patient;
// 长按的cell
@property (strong, nonatomic) NSIndexPath *longPressIndex;
@property (nonatomic) WCNCareRecordVCMode mode;
@property (nonatomic, copy) NSArray *dataSource;
@property (nonatomic, strong) UIButton *footerBtn;

@end

@implementation WCNWoundRecordVC

- (void)dealloc{
    self.dataSource = nil;
    self.patient = nil;
    self.hud = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}
- (instancetype)initWithTitle:(Patient *)patient mode:(WCNCareRecordVCMode)mode
{
    self = [super init];
    if (self) {
        self.title = @"伤口记录";
       self.navigationItem.titleView = [self customTitleView];
        _patient = patient;
        _mode = mode;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
  
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    //底部添加按钮
    [self footerAddBtnWith:@"添加伤口"];
    [self.tableView registerNib:[UINib nibWithNibName:@"WCNWoundRecordCell" bundle:nil] forCellReuseIdentifier:cellId];
    [self.tableView registerNib:[UINib nibWithNibName:cellId1 bundle:nil] forCellReuseIdentifier:cellId1];
    [self.tableView registerNib:[UINib nibWithNibName:cellid2 bundle:nil] forCellReuseIdentifier:cellid2];
    [self.tableView registerClass:[WCNPatientClassTHFV class] forHeaderFooterViewReuseIdentifier:headerId];
    UILongPressGestureRecognizer *gestureLongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(gestureLongPress:)];
    gestureLongPress.minimumPressDuration = 1;
    [self.tableView addGestureRecognizer:gestureLongPress];
    defineWeakSelf;
    // 添加下拉刷新头部控件
    self.page = 1;
    [self.tableView addLegendHeaderWithRefreshingBlock:^{
        //请求加载数据
        weakSelf.page = 1;
        [weakSelf getWoundRecords];
    } dateKey:@"WCNWoundRecordVCTableView"];
    
    [self.tableView addLegendFooterWithRefreshingBlock:^{
        weakSelf.page++;
        //请求加载数据
        [weakSelf getWoundRecords];
    }];

    [weakSelf getWoundRecords];
    
    //监听是否有 刷新通知
    [[NSNotificationCenter defaultCenter] addObserverForName:@"WoundRecordsRefreshNotification" object:nil queue:nil usingBlock:^(NSNotification *note){
        //视图在当前窗口  强制刷新  ---

        [weakSelf getWoundRecords];
    }];
    // Do any additional setup after loading the view.
    
    
    //[self.view addSubview:self.footerBtn];
    WCButton *rightBtn = [WCButton wcButtonWithType:WCButtonTypeSave];
    [rightBtn setImage:[UIImage imageNamed:@"wechat_share"] forState:UIControlStateNormal];
    rightBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [rightBtn addTarget:self action:@selector(share:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *item =[[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = item;

    NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"createTime" ascending:YES];
    NSArray *array = [[WCCoreDataStore shareStore] cwqFindWithEntity:@"WoundRecord" sort:@[sort] predicate:nil pageSize:5 currentCount:0];
    self.dataSource = [array copy];
    [self.tableView reloadData];
}

- (void)share:(UIButton *)btn{
    
    
    
    if (![WCWeixinTool isWXAppInstalled]) {
        [JCAlertView showOneButtonWithTitle:@"提示" Message:@"您还没安装微信" ButtonType:2 ButtonTitle:@"知道了" Click:^{
            
        }];
        return;
    }
    
    NSMutableString *str =[[NSMutableString alloc] init];
    
    
    [str appendFormat:@"性别:%@    年龄:%@\n",[_patient.sex isEqualToString:@"MALE"]?@"男":@"女",_patient.age?_patient.age:@""];
    
    // 格式化日期时间的类
    NSDateFormatter *dm = [[NSDateFormatter alloc] init];
    dm.dateFormat = @"yyyy-MM-dd";
    
    [str appendFormat:@"分享日期:%@\n",[dm stringFromDate:[NSDate date]]];
    [str appendFormat:@"是否糖尿病患者:%@\n",[_patient.isDiabetes integerValue]?@"是":@"否" ];
    [str appendFormat:@"白蛋白:%@",_patient.albumin?_patient.albumin:@"未知"];
    
    
    RWDropdownMenuItem *item1 =[RWDropdownMenuItem itemWithText:@"微信好友" image:[UIImage imageNamed:@"weixin_friend"] action:^(){
        [WCWeixinTool shareMediaOutWith:0 withImagename:@"icon40" urlStr:[NSString stringWithFormat:kWechatShareUrl,_patient.stringId] description:str];
        
    }];
    RWDropdownMenuItem *item2 =[RWDropdownMenuItem itemWithText:@"朋友圈" image:[UIImage imageNamed:@"weixin_juanzi"] action:^(){
        
       [WCWeixinTool shareMediaOutWith:1 withImagename:@"icon40" urlStr:[NSString stringWithFormat:kWechatShareUrl,_patient.stringId] description:str];
        
    }];
    
    
    [RWDropdownMenu presentFromViewController:self withItems:@[item1,item2] align:RWDropdownMenuCellAlignmentRight style:RWDropdownMenuStyleBlackGradient navBarImage:nil completion:nil];
    
    
}



//每次控制器的view即将显示的时候 强制刷新
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
}

/**
 *  WOUND_ADD_RECORD("伤口添加记录"),
	WOUND_NURSING_RECORD("伤口护理记录"),
	WOUND_ASSESS("伤口评估"),
	WOUND_HEALING_ASSESS("伤口愈合评估"),
	NORTON_RISK_ASSESS("Norton风险评估"),
	BRADEN_RISK_ASSESS("Braden风险评估");
  @"bodyPartCode":@"01_010"
 */
- (void)getWoundRecords
{
    [self refreshing:YES];
    
    NSLog(@"%d",[WCNetworkAccessManager sharedMg].netStatus);
    if ([WCNetworkAccessManager sharedMg].netStatus == NetworkStatusNO) {
        NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"createTime" ascending:YES];
        
        if (self.page == 1) {
            NSArray *array = [[WCCoreDataStore shareStore] cwqFindWithEntity:@"WoundRecord" sort:@[sort] predicate:nil pageSize:5 currentCount:0];
            self.dataSource = [array copy];
            [self.tableView.header endRefreshing];
            [self.tableView.footer resetNoMoreData];
            
        }else {
            NSArray *array = [[WCCoreDataStore shareStore] cwqFindWithEntity:@"WoundRecord" sort:@[sort] predicate:nil pageSize:5 currentCount:[self.dataSource count]];
            if ([array count] < 5) {
                [self.tableView.footer endRefreshing];
                [self.tableView.footer noticeNoMoreData];
            }
            NSMutableArray *muArr = [NSMutableArray arrayWithArray:self.dataSource];
            [muArr addObjectsFromArray:array];
            self.dataSource = [muArr copy];
    
        }
        [self.tableView reloadData];
        [self refreshing:NO];
    }else {
        
        __block NSInteger count = 0;
        //    MBProgressHUD *hud;
        defineWeakSelf;
        NSString *patientId = [self.patient valueForKey:@"stringId"];
        Account *account = [[WCDefaultManager shareMg] account];
        //      NSDictionary *params = @{@"recordId":patientId, @"type":@"WOUND_ADD_RECORD", @"page":@(self.page), @"rows":@10};
        NSDictionary *params = @{@"recordId":patientId, @"type":@"WOUND_ADD_RECORD", @"page":@(self.page), @"rows":@10, @"nurseId":account.stringId};
        //获取伤口记录列表
        //    if (!self.hud) {
        //        hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
        //        self.hud = hud;
        //    }
        count++;
        [[WCNetworkAccessManager sharedMg] GET:kGetWoundRecordByRecordId parameters:params success:^(NSDictionary *result){
            
            if ([result[@"success"] integerValue] == 1) {
                
                NSArray *data = result[@"data"][@"result"];
                NSLog(@"%@",data);
                NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"createTime" ascending:YES];
                //判断是上拉刷新？  还是下拉加载？
                if (weakSelf.page > 1) {
                    NSArray *dataRecord = [[WCCoreDataStore shareStore] cwqInsertWithEntity:@"WoundRecord" array:data overWrite:NO predicate:nil sort:@[sort]];
//                    NSMutableArray *muArr = [NSMutableArray arrayWithArray:weakSelf.dataSource];
//                    [muArr addObjectsFromArray:dataRecord];
                    weakSelf.dataSource = [dataRecord copy];
                    weakSelf.totalPage = [[result[@"data"] objectForKey:@"totalPage"] integerValue];
                }else {
                    
                    NSArray *dataRecord = [[WCCoreDataStore shareStore] cwqInsertWithEntity:@"WoundRecord" array:data overWrite:YES predicate:nil sort:@[sort]];
                    weakSelf.dataSource = dataRecord;
                }
            }
            
        } failure:nil netError:nil always:^{
            count--;
            if (count == 0) {
                [self refreshing:NO];
                [weakSelf.tableView reloadData];
                if (weakSelf.page > 1) {
                    [weakSelf.tableView.footer endRefreshing];
                    if (weakSelf.page - 1 == weakSelf.totalPage) {
                        
                        [weakSelf.tableView.footer noticeNoMoreData];
                    }
                }else {
                    [weakSelf.tableView.header endRefreshing];
                    [weakSelf.tableView.footer resetNoMoreData];
                }
                //            [weakSelf.hud hide:YES afterDelay:0.5];
            }
        }];
        
        /**
         *  患者档案详情
         */
        NSString *urlStrng4 = [NSString stringWithFormat:@"nursing/record/detail/%@", patientId];
        //        if (!self.hud) {
        //            hud = [[WCPopupLayerManager shareMg] showSimple:[UIApplication sharedApplication].keyWindow];
        //            self.hud = hud;
        //        }
        count++;
        [[WCNetworkAccessManager sharedMg] GET:urlStrng4 parameters:nil success:^(NSDictionary *result){
            
            [[WCCoreDataStore shareStore] updateIdPatient:self.patient withData:result[@"data"]];
            [weakSelf.tableView reloadData];
        } failure:nil netError:nil always:^{
            count--;
            if (count == 0) {
                [self refreshing:NO];
                [weakSelf.tableView reloadData];
                if (weakSelf.page > 1) {
                    [weakSelf.tableView.footer endRefreshing];
                    if (weakSelf.page - 1 == weakSelf.totalPage) {
                        
                        [weakSelf.tableView.footer noticeNoMoreData];
                    }
                }else {
                    [weakSelf.tableView.header endRefreshing];
                    [weakSelf.tableView.footer resetNoMoreData];
                }
                //                [weakSelf.hud hide:YES afterDelay:0.5];
            }
            
        }];
    
    
    }
    

}


- (void)footerAddBtnClick {

    WCNWoundDetailVC *vc = [[WCNWoundDetailVC alloc] initWith:nil mode:WCNWoundDetailVCModeAdd];
    vc.patient = self.patient;
    [self.navigationController pushViewController:vc animated:YES];

}

#pragma mark - 长按显示提示
- (void)gestureLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint tmpPointTouch = [gestureRecognizer locationInView:self.tableView];
    if (gestureRecognizer.state ==UIGestureRecognizerStateBegan) {
        NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:tmpPointTouch];
        if (indexPath == nil | indexPath.row == 0) {
            NSLog(@"not tableView");
        }else{
           self.longPressIndex = [NSIndexPath indexPathForRow:indexPath.row - 1 inSection:0];
           UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"详情", @"修改", @"删除", nil];
            [actionSheet showInView:self.view];
        
        }
    }
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {

    if (buttonIndex == 0) {
        NSDictionary *timeItem = [self dictionaryWithModel:self.dataSource[self.longPressIndex.row]];
        WCNWoundDetailVC *vc = [[WCNWoundDetailVC alloc] initWith:timeItem mode:WCNWoundDetailVCModeScan];
        vc.patient = self.patient;
        [self.navigationController pushViewController:vc animated:YES];
    }else if (buttonIndex == 1) {
        NSDictionary *timeItem = [self dictionaryWithModel:self.dataSource[self.longPressIndex.row]];
        WCNWoundDetailVC *vc = [[WCNWoundDetailVC alloc] initWith:timeItem mode:WCNWoundDetailVCModeEdit];
        vc.patient = self.patient;
        [self.navigationController pushViewController:vc animated:YES];
    
    }else if (buttonIndex == 2) {
        
        [self deleteWoundRecord];
    }
    
}

-(NSDictionary *)dictionaryWithModel:(WoundRecord *)record
{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    dic[@"bodyPartCode"] = record.bodyPartCode;
    dic[@"bodyPartName"] = record.bodyPartName;
    dic[@"createBy"] = record.createBy;
    dic[@"createTime"] = record.createTime;
    dic[@"id"] = record.id;
    dic[@"type"] = record.type;
    dic[@"description"] = record.woundDescription;
    return dic;
}
- (void)deleteWoundRecord{

    defineWeakSelf;
    NSString *message = @"此操作会删除该伤口下的所有护理录，确定要删除该伤口所有记录？";
    NSDictionary *timeItem = [self dictionaryWithModel: self.dataSource[self.longPressIndex.row]];
    
    Account *account = [[WCDefaultManager shareMg] account];
    
    //封装删除伤口记录的参数
    NSDictionary *param = @{@"woundId":timeItem[@"id"], @"recordId":self.patient.stringId, @"bodyPartCode":timeItem[@"bodyPartCode"], @"nurseId":account.stringId};
    [JCAlertView showTwoButtonsWithTitle:@"提示" Message:message ButtonType:JCAlertViewButtonTypeCancel ButtonTitle:@"取消" Click:nil ButtonType:JCAlertViewButtonTypeWarn ButtonTitle:@"确定" Click:^{
        //调用服务器接口  删除记录
        if (weakSelf.hud) {
            [weakSelf.hud removeFromSuperview];
        }
        MBProgressHUD *hud = [[MBProgressHUD alloc]init];
        
        [self.view addSubview:hud];

        [hud show:YES];
        [[WCNetworkAccessManager sharedMg] GET:kDeleteWoundRecordByRecordId parameters:param success:^(NSDictionary *result){
            CoreSVPSuccess(result[@"data"]);
            
            [weakSelf getWoundRecords];
        } failure:nil netError:nil always:^{
            [hud hide:YES afterDelay:1.0];
        }];
    }];

}

#pragma mark - <UITableViewDataSource, UITableViewDelegate>

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataSource.count + 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 85;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        if ([@"RESIDENT_PATIENT" isEqualToString:self.patient.nursingType]) {
            WCNPatientHospitalTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId1 forIndexPath:indexPath];
            [cell setBedNoText:self.patient.hosBedNo];
            [cell setLevelText:self.patient.nursingLevel];
            cell.name.text = self.patient.name;
            [cell setPartText:self.patient.woundDesc];
            [cell setStatus:self.patient.nursingStatus text:self.patient.nursingStatusName];
            return cell;
        }else {
            WCNPatientHomeTCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid2 forIndexPath:indexPath];
            cell.name.text = self.patient.name;
            [cell setLevelText:self.patient.nursingLevel];
            [cell setPartText:self.patient.woundDesc];
            cell.address.text = self.patient.address;
            [cell setStatus:self.patient.nursingStatus text:self.patient.nursingStatusName];
            return cell;
        }
        
    }
    WoundRecord *record = self.dataSource[indexPath.row - 1];
    WCNWoundRecordCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    UIImageView *typeImgSign = [cell valueForKey:@"typeImgSign"];
    typeImgSign.image = [UIImage imageNamed:@"CaseCell_BlueHeader"];
    
    UILabel *cellTitle = [cell valueForKey:@"cellTimeTitle"];
    cellTitle.text = [NSDate formattedTimeFromTimeInterval:[record.createTime longLongValue]];
    
    
    UIImageView *nurseAvatarView = [cell valueForKey:@"nurseAvatar"];
    NSString *nurseId = [NSString stringWithFormat:@"%@", record.createBy];
    UIImage *image = [[WCImageManager sharedMg] image:nurseId type:WCImageTypeNurse size:WCImageSizeSmall cache:YES];
    nurseAvatarView.image = image?image:[UIImage imageNamed:@"Nurse_default"];
    [cell setValue:nurseId forKey:@"nurseId"];
    //
    if (![[WCImageManager sharedMg] hasImage:nurseId type:WCImageTypeNurse size:WCImageSizeSmall]) {
        [[WCImageManager sharedMg] downloadImage:nurseId type:WCImageTypeNurse size:WCImageSizeSmall cache:YES success:^(UIImage *image, NSString *stringId){
            if ([stringId isEqualToString:[cell valueForKey:@"nurseId"]]) {
                nurseAvatarView.image = image;
            }
        } failure:nil];
    }
    
    cell.summary.text = [NSString stringWithFormat:@"伤口类型: %@", record.type];
    cell.part.text = [NSString stringWithFormat:@"部位: %@", record.bodyPartName];
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 0) {
        
        WCNPatientAddVC *vc = [[WCNPatientAddVC alloc] initWithPatient:self.patient];
        [self.navigationController pushViewController:vc animated:YES];
        
    }else {
    
        WCNParentCareRecordVC *vc = [[WCNParentCareRecordVC alloc] initWithTitle:self.patient mode:WCNCareRecordVCModeEdit wound:self.dataSource[indexPath.row - 1]];
        [self.navigationController pushViewController:vc animated:YES];
    }
    
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {

    return 30;

}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    WCNPatientClassTHFV *header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:headerId];
    if ([@"RESIDENT_PATIENT" isEqualToString:self.patient.nursingType]) {
        header.titleLabel.text = [NSString stringWithFormat:@"住院-%@", self.patient.hosWardName];
    } else if ([@"FAMILY_PATIENT" isEqualToString:self.patient.nursingType]) {
        header.titleLabel.text = @"家庭病床";
    }
    return header;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
